package com.example.userservice.controller;

import com.example.userservice.entity.User;
import com.example.userservice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }

    @GetMapping("/{id}")
    public Optional<User> getUserById(@PathVariable Long id) {
        return userService.getUserById(id);
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        return userService.createUser(user);
    }

    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User userDetails) {
        return userService.updateUser(id, userDetails);
    }

    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
    }

    // 新增分页查询接口
    @GetMapping("/page")
    public Page<User> getUsersByPage(@RequestParam int page, @RequestParam int size) {
        userService.test();
        return userService.getUsersByPage(PageRequest.of(page, size));
    }

    // 新增根据用户名模糊查询接口
    @GetMapping("/search/name")
    public List<User> getUsersByName(@RequestParam String name) {
        return userService.getUsersByName(name);
    }

    // 新增根据邮箱查询接口
    @GetMapping("/search/email")
    public Optional<User> getUserByEmail(@RequestParam String email) {
        return userService.getUserByEmail(email);
    }

    // 新增根据用户状态查询接口
    @GetMapping("/search/status")
    public List<User> getUsersByStatus(@RequestParam String status) {
        return userService.getUsersByStatus(status);
    }

    // 新增批量删除用户接口
    @DeleteMapping("/batch")
    public void deleteUsers(@RequestBody List<Long> ids) {
        userService.deleteUsers(ids);
    }

    // 新增根据用户名和邮箱联合查询接口
    @GetMapping("/search/nameAndEmail")
    public List<User> getUsersByNameAndEmail(@RequestParam String name, @RequestParam String email) {
        return userService.getUsersByNameAndEmail(name, email);
    }

    // 新增根据用户角色查询接口
    @GetMapping("/search/role")
    public List<User> getUsersByRole(@RequestParam String role) {
        return userService.getUsersByRole(role);
    }

    // 新增统计用户总数接口
    @GetMapping("/count")
    public long countAllUsers() {
        return userService.countAllUsers();
    }

    // 新增按角色统计用户数量接口
    @GetMapping("/count/role")
    public long countUsersByRole(@RequestParam String role) {
        return userService.countUsersByRole(role);
    }
}